import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/common_search/bean/event_bus_search_result.dart';
import 'package:dk_flutter_module_sale/r.dart';
import 'package:event_bus/event_bus.dart';

class CommonSearchBar extends StatefulWidget {
  final String placeHolder;
  final EventBus eventBus;
  final String initContent;
  final bool isShowCancel;
  final bool isSafeArea;
  //按下return（搜索键）键收起键盘
  final bool returnKeyDownKeyBoard;
  CommonSearchBar(this.eventBus,
      {this.initContent = '',
      this.placeHolder,
      this.isShowCancel = false,
      this.isSafeArea = true,
      this.returnKeyDownKeyBoard = false});

  @override
  State<CommonSearchBar> createState() {
    return _CommonSearchBarState();
  }
}

class _CommonSearchBarState extends State<CommonSearchBar> {
  TextEditingController controller;
  bool isShowDelete;

  _CommonSearchBarState();

  @override
  void initState() {
    super.initState();
    controller = TextEditingController.fromValue(
      TextEditingValue(
        text: widget.initContent,
// 保持光标在最后
        selection: TextSelection.fromPosition(TextPosition(
            affinity: TextAffinity.downstream,
            offset: widget.initContent?.length ?? 0)),
      ),
    );

    widget.eventBus
        ?.on<SetSearchContentEvent>()
        ?.listen((SetSearchContentEvent event) {
      if (objEmpty(event) || stringBlank(event.content)) {
        return;
      }
      setState(() {
        controller.value = TextEditingValue(
          text: event.content,
// 保持光标在最后
          selection: TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream,
              offset: event.content?.length ?? 0)),
        );
      });
    });
    isShowDelete = stringNotEmpty(widget.initContent);
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
            top: widget.isSafeArea ? true : false,
            bottom: widget.isSafeArea ? true : false,
            left: widget.isSafeArea ? true : false,
            right:widget.isSafeArea ? true : false,
            child: Container(
              color: Color(widget.isShowCancel ? 0xffffffff : 0xffF7F8F9),
              padding: EdgeInsets.only(top: 3.65, bottom: 3.65),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: DkRectShadow(
                      ShadowOption(
                        height: 44,
                        bgColor: Color(
                            widget.isShowCancel ? 0xffF3F3F3 : 0xffffffff),
                        borderRadius: BorderRadius.circular(4),
                        padding:
                            EdgeInsets.only(left: 14.5, top: 4.5, bottom: 5.5),
                        margin: widget.isShowCancel
                            ? EdgeInsets.only(left: 17.5)
                            : EdgeInsets.only(left: 12, right: 12),
                        child: Row(
                          children: <Widget>[
                            Image.asset(
                              R.imagesCommonSearchGlassPng,
                              width: 12,
                              height: 12,
                              fit: BoxFit.fill,
                            ),
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.only(left: 5.5),
                                child: DkTextField(
                                  DkTextFieldOption(
                                    textInputAction: TextInputAction.search,
                                    controller: controller,
                                    decoration: InputDecoration.collapsed(
                                        hintText: widget.placeHolder,
                                        hintStyle: TextStyle(
                                          color: Color(0xff999999),
                                          fontSize: 14,
                                        )),
                                    style: TextStyle(
                                        color: Color(0xff333333), fontSize: 14),
                                    autofocus: widget.returnKeyDownKeyBoard ? false : true,
                                    onChanged: (String content) {
                                      if (stringBlank(content)) {
                                        if (isShowDelete) {
                                          setState(() {
                                            isShowDelete = false;
                                          });
                                        }
                                      } else {
                                        if (!isShowDelete) {
                                          setState(() {
                                            isShowDelete = true;
                                          });
                                        }
                                      }
                                      if(widget.returnKeyDownKeyBoard) return;
                                      widget.eventBus
                                          ?.fire(SearchResultEvent(content));
                                    },
                                    onSubmitted: (content) {
                                      if(widget.returnKeyDownKeyBoard) return;
                                      widget.eventBus
                                          ?.fire(SubmitEvent(content));
                                    },
                                      onEditingComplete: (){
                                        if(widget.returnKeyDownKeyBoard) {
                                          FocusScope.of(context).requestFocus(FocusNode());
                                          widget.eventBus?.fire(SearchResultEvent(controller.text));
                                        }
                                      },
                                  ),
                                ),
                              ),
                            ),


                            DkVisibilityCompose(
                              VisibilityComposeOption.gone(
                                  (BuildContext context) {
                                return IconButton(
                                    alignment: Alignment.centerRight,
                                    padding: EdgeInsets.only(right: 7.5),
                                    icon: Icon(
                                      Icons.cancel,
                                      color: Color(0xffBFBFC2),
                                      size: 15,
                                    ),
                                    onPressed: () {
                                      setState(() {
                                        isShowDelete = false;
                                        controller.text = "";
                                        if(widget.returnKeyDownKeyBoard) return;
                                        widget.eventBus
                                            ?.fire(SearchResultEvent(""));
                                      });
                                    });
                              }, visible: isShowDelete&&!widget.returnKeyDownKeyBoard),
                            ),


                          ],
                        ),
                      ),
                    ),
                  ),
                  DkVisibilityCompose(
                    VisibilityComposeOption.gone(
                      (BuildContext context) {
                        return InkWell(
                          child: Padding(
                            padding: EdgeInsets.only(left: 10.5, right: 8),
                            child: DkText.simple("取消", 16.5, Color(0xff949494)),
                          ),
                          onTap: () {
                            RouteUtil.pop(context);
                          },
                        );
                      },
                      visible: checkBool(widget.isShowCancel),
                    ),
                  ),
                ],
              ),
            ),
          );
  }
}
